#-*-coding:utf-8-*-
import os
import pymysql
import functools
from app.database_config import *
from app.static.interface_auto.common import common
from collections import namedtuple

nameStil = namedtuple("St",["start", "end"])


def exception_catch(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except Exception as e:
            self.close()
            common.logInfo(e)
    return wrapper


class MySql(object):

    def __init__(self):
        self.__db = pymysql.connect(host=database_host, user=database_username, password=database_password, database=database1)
        self.__dbc = self.__db.cursor()
        self.__all_table = ("case_list", "interface_list", "interface_task_list", "list", "project_list", "users")
        self.__db.set_charset('utf8')
        self.execute('SET NAMES utf8;')
        self.execute('SET CHARACTER SET utf8;')
        self.execute('SET character_set_connection=utf8;')

    def get_db(self):
        return self.__db

    def get_dbc(self):
        return self.__dbc

    @exception_catch
    def commit_sql(self):
        self.__db.commit()

    @exception_catch
    def close(self):
        self.__dbc.close()
        self.__db.close()

    @exception_catch
    def get_all_connect(self):
        #type: () -> tuple
        return self.__dbc.fetchall()

    @exception_catch
    def get_one_connect(self):
        return self.__dbc.fetchone()

    @exception_catch
    def get_any_connect(self, size):
        return self.__dbc.fetchmany(size)

    @exception_catch
    def create_table(self, sql):
        if isinstance(sql, str) and sql.strip().endswith(";"):
            self.__dbc.execute(sql)
            common.logInfo("{} 创建成功".format(self.__get_name(sql)))
        if os.path.isfile(sql):
            with open(sql, "r") as f:
                all_lines = f.readlines()
                start = 0
                for line in all_lines:
                    if line.strip().endswith(";"):
                        sql_str = ("".join(all_lines[start:all_lines.index(line, start) + 1]))
                        start = all_lines.index(line, start) + 1
                        self.__dbc.execute(sql_str)
                        log_cent = self.__get_name(sql_str)
                        if log_cent:
                            common.logInfo(log_cent)
        self.commit_sql()

    @exception_catch
    def delte_table(self, table, **kwargs):
        sql = "DROP TABLE {table}".format(table=table)
        if table in self.__all_table:
            self.execute(sql)

    def show_tables(self):
        # type: () -> tuple
        sql_str = "SHOW TABLES;"
        self.execute(sql_str)
        return tuple([one for tup in self.get_all_connect() for one in tup])

    @exception_catch
    def get_all_task(self):
        sql = 'SELECT * FROM interface_task_list WHERE is_settime_task = 1 AND settime_task_status = 1;'
        self.execute(sql)
        return self.get_all_connect()

    @exception_catch
    def execute(self, sql=None, args=None):
        if sql:
            print(sql)
            print(args)
            self.__dbc.execute(sql, args)
            self.__db.commit()

    @exception_catch
    def inser_into(self):
        pass

    def delete_data(self, table, **kwargs):
        sql_where = "DELETE FROM {table} WHERE {args}".format(table=table, args=kwargs)
        pass

    @exception_catch
    def select_data(self):
        pass

    def __get_name(self, st):
        #type: (str) -> str
        if "(" in st:
            n = nameStil(st.lower().index("table")+len("table"), st.lower().index("("))
            return "创建 {} 表成功".format(st[n.start:n.end].strip().replace("`", "").strip())
        if "delete" in st.lower() or "drop" in st.lower():
            if "if" in st.lower():
                n = nameStil(st.lower().index("table if exists") + len("table if exists"), st.lower().index(";"))
            else:
                n = nameStil(st.lower().index("table")+len("table"), st.lower().index(";"))
            return "删除 {} 表成功".format(st[n.start:n.end].replace("`", "").strip())

    def __new__(cls):
        #type: () -> MySql
        if hasattr(cls, "instance"):
            print("对象获取成功")
            return cls.instance
        cls.instance = super(MySql, cls).__new__(cls)
        print("对象创建成功")
        return cls.instance


SQL = MySql()

if __name__ == "__main__":
    n = MySql()
    # # n.create_table(r"/Users/xz/pj/manager-server/tables.sql")
    # n.create_table(r"D:\pj\zhe.xiao\manager_server\tables.sql")
    # i = n.show_tables()
    # print(i)
    n.closee()
    # ii = [random.choice(xrange(10)) for i in xrange(10)]
    # print("qi:", ii)
    # for i in xrange(len(ii)):
    #     for j in xrange(i+1,len(ii)):
    #         if ii[j] < ii[i]:
    #             ii[i], ii[j] = ii[j], ii[i]
    # print("hou:", ii)





